package com.itfreer.data.general;

import com.itfreer.utils.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * 类功能说明 定义表关系操作静态辅助类
 */
public class RelationOption {

	/**
	 * 填充实体类的子表信息
	 * 
	 * @param table
	 *            父表对象
	 * @param entity
	 *            当前记录
	 * @param fillChildType
	 *            填充类型
	 * @param useOldValue
	 *            是否使用旧值做为关键字查询子表
	 * @param addCaptionField
	 */
	public static void FillEntityChild(ITable table, RowBase entity,
			boolean addCaptionField) {
		if (table == null)
			return;

		if (entity == null)
			return;

		RelationNode node = table.getRelation();
		if (node == null || node.getChildRelationNode() == null
				|| node.getChildRelationNode().size() <= 0)
			return;

		HashMap<String, RelationInfo> cTable = node.getChildRelationNode();
		Set<String> childRelationNodeKeys = node.getChildRelationNode()
				.keySet();
		for (String childRelationNodeKey : childRelationNodeKeys) {
			ITable childTable = table.getTableFactory().openTable(
					childRelationNodeKey);
			if (childTable == null)
				continue;

			IQueryMap queryMap = new QueryMap();
			HashMap<String, String> foreignkeyMap = cTable
					.get(childRelationNodeKey).Foreignkey;
			Set<String> foreignkeys = foreignkeyMap.keySet();
			for (String foreignkey : foreignkeys) {
				queryMap.getWhereMap().put(foreignkeyMap.get(foreignkey),
						entity.getValue(foreignkey));
			}

			if (queryMap.getWhereMap().size() > 0) {
				queryMap.setSelectFields(childTable.getSelectFields(false));
				queryMap.setAddCaptionField(addCaptionField);

				List<RowBase> entityList = (List<RowBase>) childTable
						.getEntityList(RowBase.class, queryMap);
				if (entity.getChildValues() == null)
					entity.setChildValues(new HashMap<String, List<RowBase>>());
				if (entity.getChildValues().containsKey(childRelationNodeKey))
					entity.getChildValues().put(childRelationNodeKey,
							entityList);
				else
					entity.getChildValues().put(childRelationNodeKey,
							entityList);

				if (entityList != null && entityList.size() > 0) {
					for (RowBase item : entityList) {
						FillEntityChild(childTable, item, addCaptionField);
					}
				}
			} else {
				// 填充结构
				if (entity.getChildValues() == null)
					entity.setChildValues(new HashMap<String, List<RowBase>>());
				if (entity.getChildValues().containsKey(childRelationNodeKey))
					entity.getChildValues().put(childRelationNodeKey, null);
				else
					entity.getChildValues().put(childRelationNodeKey, null);
			}
		}
	}

	/**
	 * 填充实体类的子表信息
	 * 
	 * @param table
	 *            父表对象
	 * @param entity
	 *            当前记录
	 * @param childName
	 *            子表名称，如果名称为空或null，则为所有子表
	 * @param useOldValue
	 *            是否使用旧值做为关键字查询子表
	 * @param addCaptionField
	 */
	public static void FillEntityChild(ITable table, RowBase entity,
			String childName, HashMap<String, Object> orderByMap,
			boolean addCaptionField) {
		if (table == null || entity == null)
			return;

		RelationNode node = table.getRelation();
		if (node == null || node.getChildRelationNode() == null
				|| node.getChildRelationNode().size() <= 0)
			return;

		Set<String> childRelationNodeKeys = node.getChildRelationNode()
				.keySet();
		for (String childRelationNodeKey : childRelationNodeKeys) {
			if (StringUtils.IsNullOrSpace(childName)
					|| childRelationNodeKey.toUpperCase().trim()
							.equals(childName.toUpperCase().trim())) {
				ITable childTable = table.getTableFactory().openTable(
						childRelationNodeKey);
				if (childTable == null)
					continue;

				IQueryMap queryMap = new QueryMap();
				HashMap<String, String> foreignkeyMap = node
						.getChildRelationNode().get(childRelationNodeKey).Foreignkey;
				Set<String> foreignkeyKeys = foreignkeyMap.keySet();
				for (String foreignkeyKey : foreignkeyKeys) {
					queryMap.getWhereMap().put(
							foreignkeyMap.get(foreignkeyKey),
							entity.getValue(foreignkeyKey));
				}
				queryMap.setOrderByMap(orderByMap);

				if (queryMap.getWhereMap().size() > 0) {
					queryMap.setSelectFields(childTable.getSelectFields(false));
					queryMap.setAddCaptionField(addCaptionField);

					List<RowBase> entityList = childTable.getEntityList(
							RowBase.class, queryMap);
					if (entity.getChildValues() == null)
						entity.setChildValues(new HashMap<String, List<RowBase>>());
					if (entity.getChildValues().containsKey(
							childRelationNodeKey))
						entity.getChildValues().put(childRelationNodeKey,
								entityList);
					else
						entity.getChildValues().put(childRelationNodeKey,
								entityList);
				} else {
					// 填充结构
					if (entity.getChildValues() == null)
						entity.setChildValues(new HashMap<String, List<RowBase>>());
					if (entity.getChildValues().containsKey(
							childRelationNodeKey))
						entity.getChildValues().put(childRelationNodeKey, null);
					else
						entity.getChildValues().put(childRelationNodeKey, null);
				}
			}
		}
	}

	/**
	 * 填充中间表子表数据，并根据中间表与关联的另外一张主表将外键关系，将另外一张主表的信息一起填充给中间子表记录
	 * 如，用户表，用户角色表，角色表。当获取用户角色表时，可将角色表的信息一起查询出来，并给中间表子间填充
	 * 如果另外一张主表中的字段在中间表中存在，则另外一张主表的字段改为字段名+"_OO"
	 * 
	 * @param table
	 *            当前表对象
	 * @param entity
	 *            当前数据对象
	 * @param childName
	 *            中间表名称，必需存在
	 * @param tagetTableName
	 *            与中间表关联的另外一张主表
	 * @param relation
	 *            中间表与另外一张主表的外键关系,key:中间表， value:另外一张主表
	 * @param orderByMap
	 *            排序对象
	 * @param addCaptionField
	 *            是否添加转议字段
	 */
	public static void FillEntityChild(ITable table, RowBase entity,
			String childName, String tagetTableName,
			HashMap<String, String> relation,
			HashMap<String, Object> orderByMap, boolean addCaptionField) {
		if (table == null || entity == null)
			return;
		if (StringUtils.IsNullOrSpace(childName)
				|| StringUtils.IsNullOrSpace(tagetTableName)
				|| relation == null || relation.size() <= 0) {
			return;
		}
		FillEntityChild(table, entity, childName, orderByMap, addCaptionField);
		if (entity.getChildValues() == null
				|| !entity.getChildValues().containsKey(childName)) {
			return;
		}
		List<RowBase> childRows = entity.getChildValues().get(childName);
		if (childRows == null || childRows.size() <= 0) {
			return;
		}

		ITable tagetTable = table.getTableFactory().openTable(tagetTableName);
		if (tagetTable == null) {
			return;
		}

		IQueryMap queryFilter = new QueryMap();
		Set<String> foreignkeyKeys = relation.keySet();
		List<HashMap<String, Object>> mapList = new ArrayList<HashMap<String, Object>>();
		for (RowBase row : childRows) {
			HashMap<String, Object> andMap = new HashMap<String, Object>();
			for (String foreignkeyKey : foreignkeyKeys) {
				String field = relation.get(foreignkeyKey);
				Object value = row.getValue(foreignkeyKey);
				andMap.put(field, value);
			}
			mapList.add(andMap);
		}
		queryFilter.getWhereMap().put("or", mapList);
		queryFilter.setAddCaptionField(addCaptionField);

		List<RowBase> tagetRows = tagetTable.getEntityList(RowBase.class,
				queryFilter);
		if (tagetRows == null || tagetRows.size() <= 0) {
			return;
		}

		// 拼接
		for (int i = 0; i < childRows.size(); i++) {
			RowBase row = childRows.get(i);
			String key = "";
			for (String foreignkeyKey : foreignkeyKeys) {
				key += row.getValue(foreignkeyKey) + "_field_field_";
			}

			for (RowBase tagRow : tagetRows) {
				String tagkey = "";
				for (String foreignkeyKey : foreignkeyKeys) {
					tagkey += tagRow.getValue(relation.get(foreignkeyKey))
							+ "_field_field_";
				}
				if (key.equals(tagkey)) {
					Set<String> tagRowKey = tagRow.keySet();
					for (String item : tagRowKey) {
						if (!row.containsKey(item)) {
							row.put(item, tagRow.get(item));
						} else {
							if (!row.containsKey(item + "_OO")) {
								row.put(item + "_OO", tagRow.get(item));
							}
						}
					}
					break;
				}
			}
		}
	}
}